<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
namespace app\api\controller;

use base\Openkongfz;  
use think\Db;
use app\service\GoodsService;
use app\plugins\oss_1jian\service\OssService;
use app\service\PluginsService;

/**
 * 商品
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class Kongfz extends Common
{
    /**
     * [__construct 构造方法]
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  0.0.1
     * @datetime 2016-12-03T12:39:08+0800
     */
    public function __construct()
    {
        // 调用父类前置方法
        parent::__construct();
    }
    
    
    
    
    public function index(){
        $url='https://open.kongfz.com/v1/oauth2/authorize?appId=27&responseType=code&state=kongfz.shop.item.list&redirectUri=http://dianshu.chaoshang666.com/index.php/api/kongfz/kongfzcode';
        
        $this->redirect($url,302);
    
    }
    

    
    public function kongfzcode(){
        
    set_time_limit(0);
        
        
        $code=input("get.code");
        $url="https://open.kongfz.com/v1/oauth2/token";
        $data=[
            'code'=>$code,
            'grantType'=>'authorization_code',
            'appId'=>'27',
            'appSecret'=>'4dfa306de36925f61dad3a60330f9741e8808dc918ce7041f2dd53e63c19c3e9',
            'redirectUri'=>'http://dianshu.chaoshang666.com/index.php/api/kongfz/getdata',
            
        ];
        
        $Openkongfz =   new Openkongfz();
        $result  = $Openkongfz->HttpRequestPost($url,$data,true);
        
        if($result['errCode']==0){
            $accessToken=$result['result']['accessToken'];
            dump($accessToken);exit;
            if(input("get.state")=='kongfz.common.category'){
                $this->addcat($accessToken);
            }elseif(input("get.state")=='kongfz.shop.item.list'){
                $this->addgoods($accessToken,'sale',26,100);
            }
            
        }else{
            $this->index();
        }
   
     
    }
    
 
    

    
    
    //添加产品
    public function addgoods(){
        $Openkongfz =   new Openkongfz(27,'4dfa306de36925f61dad3a60330f9741e8808dc918ce7041f2dd53e63c19c3e9');
        
        $pageNum=Db::name("config")->where(['only_tag'=>'kfz_page'])->value('value');
        
    
        $dat=[
             'method'=>'kongfz.shop.item.list',
             'accessToken'=>'3b97744f5bb6f19e8ed01b2ca7e8bd5c60cd4eb47388788004a4dfd62a6ad430',
             'type'=>'sale',//$type,
             'pageNum'=>$pageNum,
             'pageSize'=>100,
        ];
        
        
        $res=$Openkongfz->selectGoods($dat);
        
    
    
    
        if(!empty($res['successResponse']['list'])){
            
            $list=$res['successResponse']['list'];
            
    
            
            foreach ($list as $k=>$v){
                
                $kfz_id=Db::name("goods")->where(['kfz_id'=>$v['itemId']])->find();
                
            //  dump($kfz_id);
                if(!empty($kfz_id)){
                    continue;
                }

                //判断是否有货号
                if(empty($v['itemSn'])){
                    continue;
                }
                    
               
                    
                    
                //  dump($v['imgUrl']);
            
                
                if(substr($v['imgUrl'], -6,1)=="_"){
                    $imgurl=explode(".",$v['imgUrl']);
                    $imgurl_1=substr($imgurl[0], 0,-1);
                
                    $o_url=$imgurl_1."o.".$imgurl[1];
                    
                    
                    
                    //原图
                    $file_url="https://www.kfzimg.com/".$o_url;
                
                    $filesize = @getimagesize($file_url);
                //  dump(!$filesize);
                    
                
                    if(!$filesize){
                        continue;
                    }
                }else{
                    $file_url="https://www.kfzimg.com/".$v['imgUrl'];
                }
                
                
                
                
                
                //保存图片路径
                $save_to='./static/upload/kongfz/'.pathinfo($file_url)['basename'];
            
                $content = file_get_contents($file_url);

                //下载
                $r=$Openkongfz->dlfile($content,$save_to);
            
                
                $ret_data = PluginsService::PluginsData("oss_1jian",[],true);  //获取插件配置数据
                

                $object = substr($save_to,2);

                //调用oss插件           
               
               

    
                $ossClient=new  OssService($ret_data['data']["OSS_ACCESS_ID"],$ret_data['data']["OSS_ACCESS_KEY"],$ret_data['data']["OSS_TEST_BUCKET"],$ret_data['data']["OSS_ENDPOINT"],$ret_data['data']["OSS_DOMAIN"]);

                $r = $ossClient->uploadoss($object, $content);
        
   
            //  下载成功
                
                if($r){
                    
                    //调用裁剪方法分成3张不同尺寸的图片上传到oss 返回3张图片的地址
                
                    //调用oss方法上传原图
            

                    //获取作者
                    if(!empty($v['author'])){
                        $v['author']=Db::name("author")->where(['name'=>$v['author']])->value('id');
                    }

                    //组装产品数据调用添加产品方法添加产品
                    $category_id=Db::name("goods_category")->where(['kfz_id'=>$v['catId']])->value('id');
                    
                
                    
                    if($v['certifyStatus']=='notCertified' || $v['certifyStatus']=='waitApproved'){
                            $status=0;
                    }elseif($v['certifyStatus']=='certified'){
                            $status=1;
                    }elseif($v['certifyStatus']=='frozen' || $v['certifyStatus']=='failed'){
                            $status=2;
                    }
                
                    $save_to='http://image.kongz.com/static/upload/kongfz/'.pathinfo($file_url)['basename'];
                  
                    $params=[
                        'title'=>$v['itemName'],
                        'simple_desc'=>$v['itemName'],
                        'category_id'=>$category_id,
                        'press'=>$v['press'],
                        'author'=>$v['author'],
                        'pubdate'=>$v['pubDate'],
                        'quality'=>$v['quality'],
                        'status'=>$status,
                        'isbn'=>$v['isbn'],
                        'weightPiece'=>$v['weightPiece'],
                        'warehouse_id'=>1,
                        'original_price'=>$v['oriPrice']==0?$v['price']:$v['oriPrice'],
                        'shelf_number'=>$v['itemSn'],
                        'beginSaleTime'=>$v['beginSaleTime'],
                        'endSaleTime'=>$v['endSaleTime'],
                        'specifications_price'=>[$v['price']],
                        'specifications_inventory'=>[$v['number']],
                        'specifications_weight'=>[$v['weight']],
                        'specifications_original_price'=>[$v['oriPrice']==0?$v['price']:$v['oriPrice']],
                        'upd_time'=>strtotime($v['updateTime']),
                        'is_delete_time'=>$v['isDelete']==0?0:time(),
                        'is_shelves'=>$v['isOnSale'],
                        'price'=>$v['price'],
                        'productArea'=>$v['productArea'],
                        'inventory'=>$v['number'],
                        'years'=>$v['years'],
                        'discount'=>$v['discount'],
                        'add_time'=>$v['addTime'],
                        'booksList'=>'',
                        'photo'=>[$save_to],
                        'binding'=>5,
                        'aid'=>5,
                        'kfz_id'=>$v['itemId'],
                    ];
                    
                
          
                    dump(GoodsService::GoodsSave($params));
                    
                      // dump($params);exit;
                    //echo "<img src='http://".$_SERVER['SERVER_NAME']."/".$save_to."'><br/>"   ;

                }
                
            
            }
    //  exit;
            Db::name("config")->where(['only_tag'=>'kfz_page'])->update(['value'=>$pageNum+1]);
        //  sleep(2);
        //  $this->addgoods();
        }
        
    }
    
    



       //添加分类
    public function addcat($accessToken){
        $Openkongfz =   new Openkongfz();
        $dat=[
             'method'=>'kongfz.common.category',
             'accessToken'=>$accessToken,
             
        ];
        
        $res=$Openkongfz->selectGoods($dat);
        
        $list=$res['successResponse'];
        
        foreach ($list as $k=>$v){
            
            //dump($v);exit;
            $data=[
                'pid'=>0,
                'name'=>$v['name'],
                'add_time'=>time(),
                'kfz_id'=>empty($v['id'])?0:$v['id'],
            ];
            
            $pid=Db::name("goods_category")->insertGetid($data);
            echo "===1".$v['name']."<br/>";
            
             foreach ($v['children'] as $kk=>$vv){
                        $data=[
                            'pid'=>$pid,
                            'name'=>$vv['name'],
                            'add_time'=>time(),
                            'kfz_id'=>empty($vv['id'])?0:$vv['id'],
                        ];
                        
                        $pid1=Db::name("goods_category")->insertGetid($data);
                    echo "=======2".$vv['name']."<br/>";
                foreach ($vv['children'] as $kkk=>$vvv){
                    
                            $data=[
                            'pid'=>$pid1,
                            'name'=>$vvv['name'],
                            'add_time'=>time(),
                            'kfz_id'=>empty($vvv['id'])?0:$vvv['id'],
                        ];
                        
                        $pid2=Db::name("goods_category")->insertGetid($data);
                    
                        echo "===========3".$vvv['name']."<br/>";
                        
                        if(empty($vvv['children'])){
                            continue;
                        }
                    foreach ($vvv['children'] as $kkkk=>$vvvv){
                                $data=[
                            'pid'=>$pid2,
                            'name'=>$vvvv['name'],
                            'add_time'=>time(),
                            'kfz_id'=>empty($vvvv['id'])?0:$vvvv['id'],
                        ];
                        
                        $pid3=Db::name("goods_category")->insertGetid($data);
                                echo "==============4".$vvvv['name']."<br/>";
                                
                                if(empty($vvvv['children'])){
                                    continue;
                                }
                            foreach ($vvvv['children'] as $kkkkk=>$vvvvv){
                                    $data=[
                                        'pid'=>$pid3,
                                        'name'=>$vvvvv['name'],
                                        'add_time'=>time(),
                                        'kfz_id'=>empty($vvvvv['id'])?0:$vvvvv['id'],
                                    ];
                                    
                                    $pid4=Db::name("goods_category")->insertGetid($data);
                                        echo "=================5".$vvvvv['name']."<br/>";
                                        
                                            if(empty($vvvvv['children'])){
                                                    continue;
                                                }
                                            foreach ($vvvvv['children'] as $kkkkkk=>$vvvvvv){
                                                    $data=[
                                                        'pid'=>$pid4,
                                                        'name'=>$vvvvvv['name'],
                                                        'add_time'=>time(),
                                                        'kfz_id'=>empty($vvvvvv['id'])?0:$vvvvvv['id'],
                                                    ];
                                                    
                                                    $pid5=Db::name("goods_category")->insertGetid($data);
                                                        echo "====================6".$vvvvvv['name']."<br/>";
                                                        if(empty($vvvvvv['children'])){
                                                            continue;
                                                        }
                                                    foreach ($vvvvvv['children'] as $kkkkkkk=>$vvvvvvv){
                                                                echo "=======================8".$vvvvvvv['name']."<br/>";
                                                    }
                                            }
                            }
                    }
                }
             }
            
            
                
                echo "=============================<br/>";
            
        }
        
        
    }
    

    

    

}
?>